package com.ajhlp.spring_modules.db.multiSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.datasource.DriverManagerDataSource;

import com.ajhlp.spring_modules.db.multiSource.metaModel.DBSource_BasicInfo;
import com.ajhlp.spring_modules.db.multiSource.metaModel.DBSource_DataField;
import com.ajhlp.spring_modules.db.multiSource.metaModel.DBSource_DataSet;

/**
 * 数据库操作工具
 * @author ajhlp
 *
 */
public class DBServerUtil {

	/**
	 * 查询所有表、视图基本信息
	 * @param connection 数据连接
	 * @return
	 */
	public static List<DBSource_DataSet> queryAllDataSetInfo(Connection connection){
		List<DBSource_DataSet> sets = new ArrayList<DBSource_DataSet>();
		
		try {
			ResultSet resultSet = connection.getMetaData().getTables(connection.getCatalog(), null, null, new String[]{"TABLE","VIEW"});
			while (resultSet.next()) {
				DBSource_DataSet dataSet = new DBSource_DataSet();
				dataSet.setName(resultSet.getString("TABLE_NAME"));
				dataSet.setDescription(resultSet.getString("REMARKS"));
				if("VIEW".equals(resultSet.getString("TABLE_TYPE"))){
					dataSet.setEditable(Boolean.FALSE);
				}else{
					dataSet.setEditable(Boolean.TRUE);
				}
				sets.add(dataSet);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return sets;
	}
	
	public static List<DBSource_DataField> queryAllDataFieldInfo(Connection connection,String tableName){
		List<DBSource_DataField> fields = new ArrayList<DBSource_DataField>();
		try {
			ResultSet resultSet = connection.getMetaData().getColumns(connection.getCatalog(), null, tableName, null);
			while (resultSet.next()) {
				DBSource_DataField dataField = new DBSource_DataField();
				dataField.setName(resultSet.getString("COLUMN_NAME"));
				dataField.setDescription(resultSet.getString("REMARKS"));
				dataField.setType(resultSet.getString("TYPE_NAME"));
				fields.add(dataField);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return fields;
		
	}
	
	public static DriverManagerDataSource getDataSource(DBSource_BasicInfo basicInfo){
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://10.71.196.147:3306/city_plat?useUnicode=true&characterEncoding=utf-8");
		dataSource.setUsername("test");
		dataSource.setPassword("123456");
		return dataSource;
	}
	
}
